<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="ctx" th:content="${#httpServletRequest.getContextPath()}"/>
    <title>用户列表</title>
    <link rel="stylesheet" th:href="@{/css/admin/base-v2.css}">
    <link rel="stylesheet" th:href="@{/lib/font-awesome/4.7.0/css/font-awesome.min.css}">
    <link rel="stylesheet" th:href="@{/css/admin/app.css}">
</head>

<body>

<div class="app-page">

    <div class="app-page-content">

        <div class="app-card">
            <div class="app-card-body">
                <div class="app-card-body-con">
                    <!-- 过滤器 -->
                    <form class="filter">
                        <div class="filter-group">
                            <div class="filter-item">
                                <div class="form-item row">
                                    <div class="label">
                                        <label>所属部门</label>
                                    </div>
                                    <div class="body">
                                        <input type="hidden" class="departmentId z-hide departmentId" name="departmentId" th:value="${departmentId}" >
                                        <div class="input-group">
                                            <input type="text" readonly="readonly"
                                                   style="background-color: #f5f7fa;border-color: #e4e7ed;color: #c0c4cc;cursor: not-allowed;"
                                                   class="departmentName" name="departmentName" th:value="${departmentName}" data-name="部门">
                                            <span class="input-group-addon select-department"><i class="fa fa-align-center"></i></span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="filter-item">
                                <div class="form-item row">
                                    <div class="label"><label>状态</label></div>
                                    <div class="body">
                                        <select name="status" id="">
                                            <option value="">全部</option>
                                            <option value="1">禁用</option>
                                            <option value="0">启用</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            <div class="filter-item">
                                <div class="form-item row">
                                    <div class="label"><label>账号</label></div>
                                    <div class="body">
                                        <input type="text" placeholder="请输入账号" name="userName">
                                    </div>
                                </div>
                            </div>
                            <div class="filter-item">
                                <button class="z-btn z-primary">查询</button>
                            </div>
                            <div style="display: none">
                                <input name="pageNum" th:value="${pageNum}">
                                <input name="pageSize" th:value="${pageSize}">
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        <div class="app-card">
            <div class="app-card-body">
                <div class="app-card-body-con">

                    <div class="z-btn-group">
                        <button class="j-btn-control z-btn z-default btn-add">创建用户</button>
                        <button class="j-btn-control z-btn z-default btn-batch-able">批量启用</button>
                        <button class="j-btn-control z-btn z-default btn-batch-disable">批量禁用</button>
                    </div>

                    <table class="z-table">
                        <thead>
                        <th>
                            <input type="checkbox" class="input j-checkbox-all">
                        </th>
                        <th>账号</th>
                        <th>姓名</th>
                        <th>所属部门</th>
                        <th>手机号</th>
                        <th>所属角色</th>
                        <th>状态</th>
                        <th>操作</th>
                        </thead>
                        <tbody>
                        <tr th:each="user: ${userList}" th:attr="data-id=${user.userId},
                               data-departmentid=${user.departmentId},
                               data-super-admin-user=${user.superAdminUser},
                               data-departmentname=${user.departmentName},
                               data-userName=${user.userName},
                               data-realname=${user.realname},
                               data-mobilePhone=${user.mobilePhone},
                               data-email=${user.email},
                               data-belongRoleIds=${user.belongRoleIds},
                               data-userType=${user.userType},
                               data-status=${user.status}">
                            <td>
                                <input type="checkbox" class="input j-checkbox">
                            </td>
                            <td th:text="${user.userName}"></td>
                            <td th:text="${user.realname}"></td>
                            <td th:text="${user.departmentName}"></td>
                            <td th:text="${user.mobilePhone}"></td>
                            <td th:text="${user.belongRole}"></td>
                            <div th:switch="${user.status}">
                                <td th:case="1">禁用</td>
                                <td th:case="0">启用</td>
                            </div>
                            <div th:switch="${user.superAdminUser}">
                                <!--不是超级管理员用户-->
                                <div th:case="1">
                                    <td class="btn-group" th:switch="${user.status}">
                                        <a class="btn-enable" th:case="1">启用</a>
                                        <a class="btn-disable" th:case="0">禁用</a>
                                        <a class="btn-detail">修改</a>
                                        <a class="btn-reset">重置密码</a>
                                    </td>
                                </div>
                                <div th:case="0">
                                    <td></td>
                                </div>
                            </div>
                        </tr>
                        </tbody>
                    </table>

                    <!-- 分页 -->
                    <div class="app-card-body">
                        <div class="pagination z-pat z-fr"></div>
                    </div>
                </div>
            </div>
        </div>


    </div>
</div>

<!--新增/编辑-->
<div class=" popup-default z-popup z-fixed z-df z-flex-cc z-hide">
    <div class="bg" data-popup-close=""></div>
    <div class="section popup-add z-hide">
        <div class="title">创建用户</div>
        <div class="content" id="userForm">
            <form>
                <div class="form-item row" style="display: none">
                    <div class="label">
                        <label>ID</label>
                    </div>
                    <div class="body">
                        <input type="hidden" name="userId" class="userId">
                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>账号</label>
                    </div>
                    <div class="body">
                        <input type="text" value="" placeholder="请输入账号，如abcD123" class="userName"
                               name="userName" data-name="用户名" data-rule="required,length" minlength="1"
                               maxlength="10">

                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>姓名</label>
                    </div>
                    <div class="body">
                        <input type="text" value="" placeholder="请输入姓名" class="realname" name="realname"
                               data-name="真实姓名" data-rule="length" maxlength="32"  onkeyup="this.value=this.value.replace(/\s+/g,'')">

                    </div>
                </div>
                <div class="form-item row pwd">
                    <div class="label">
                        <label>登录密码</label>
                    </div>
                    <div class="body pwd-item" data-limit="0" data-input-name="" data-data-key="resize">
                        <input type="password" value="" placeholder="请输入登陆密码" class="password" name="password" data-name="登录密码" data-rule="required,password">
                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>手机号</label>
                    </div>
                    <div class="body">
                        <input type="text" value="" placeholder="请输入手机号" class="mobilePhone" name="mobilePhone" data-name="手机号" data-rule="required">
                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>邮箱</label>
                    </div>
                    <div class="body">
                        <input type="text" value="" placeholder="请输入邮箱" class="email" name="email" data-name="邮箱" data-rule="required">
                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>所属部门</label>
                    </div>
                    <div class="body">
                        <input type="hidden" class="departmentId z-hide departmentId" name="departmentId" >
                        <div class="input-group">
                            <input type="text" disabled="disabled" class="departmentName" name="departmentName" data-name="部门" data-rule="required">
                            <span class="input-group-addon select-department"><i class="fa fa-align-center"></i></span>
                        </div>
                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>员工类型</label>
                    </div>
                    <div class="body">
                        <label style="margin-right:10px;">
                            <input class="input" type="radio" name="userType" value="1" th:text="外包"
                                   style="margin-right:5px;">
                        </label>
                        <label style="margin-right:10px;">
                            <input class="input" type="radio" name="userType" value="0" th:text="正式"
                                   style="margin-right:5px;">
                        </label>
                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>角色</label>
                    </div>
                    <div class="roleIds body">
                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>状态</label>
                    </div>
                    <div class="body">
                        <label style="margin-right:10px;">
                            <input class="input" type="radio" name="status" value="1" th:text="禁用"
                                   style="margin-right:5px;">
                        </label>
                        <label style="margin-right:10px;">
                            <input class="input" type="radio" name="status" value="0" th:text="启用"
                                   style="margin-right:5px;">
                        </label>
                    </div>
                </div>
            </form>
            <div class="z-btn-group">
                <a class="btn-submit z-btn z-primary user-comfirm">确定</a>
                <a class="z-btn z-default" data-popup-close="">取消</a>
            </div>
        </div>
    </div>
    <div class="popup-detail section z-hide"></div>
</div>

<!-- 重置密码 -->
<div class="popup-reset popup-default z-popup z-fixed z-df z-flex-cc z-hide">
    <div class="bg" data-popup-close></div>
    <div class="body">
        <div class="title">重置密码</div>
        <div class="content">
            <form>
                <div class="form-item row">
                    <div class="label">
                        <label>新密码</label>
                    </div>
                    <div class="body">
                        <input type="password" name="password" data-name="密码" data-rule="required">
                    </div>
                </div>
                <div class="z-hide">
                    <input type="text" name="userId">
                </div>
            </form>
            <div class="z-btn-group">
                <a class="btn-submit z-btn z-primary">确定</a>
                <a class="z-btn z-default" data-popup-close>取消</a>
            </div>
        </div>
    </div>
</div>

<script th:src="@{/lib/jquery.min.js}"></script>
<script th:src="@{/lib/layer-v3.1.1/layer/layer.js}"></script>
<script th:src="@{/js/popup.js}"></script>
<script th:src="@{/js/form.js}"></script>
<script th:src="@{/js/admin/app.js}"></script>
<script th:src="@{/js/pagination.js}"></script>
<script th:src="@{/js/table.js}"></script>
<script type="text/javascript" th:inline="javascript">
    //获取context path
    var context = $("meta[name='ctx']").attr("content") || '';

    // 从URL加载搜索数据
    $(".filter").formLoad(App.query);

    //处理分页
    var pageNum = [[${pageNum}]];
    var pageSize = [[${pageSize}]];
    var total = [[${total}]];
    var pagination = new Pagination(".pagination", {
        pageIndex: pageNum, // 当前页数
        pageSize: pageSize, // 每页数量
        count: total, // 总条数
        maxButtonCount: 5, // 分页按钮数量(可选)
        // 分页切换事件
        onPageChanged: function (pageIndex) {
            window.location.href = context + "/user/list?pageNum=" + pageIndex + "&pageSize=" + pageSize;
        }
    })
    //监听
    $(function () {
        eventEmit();

    })

    // 获取表格中选择的ID
    function getSelecteId() {
        let temp = [];
        $('tbody [type="checkbox"]').each(function (index, element) {
            if (element.checked == true) {
                var superAdminUser = $(this).parents('tr,.tr').data('superAdminUser');
                console.log("superAdminUser:"+superAdminUser);
                temp.push($(this).parents('tr,.tr').data('id'));
            }
        })
        return temp.join(',');
    }


    //检查参数
    function isBlank(param) {
        if(undefined === param){
            return true;
        }
        if(null == param){
            return true;
        }
        if("" === param){
            return true;
        }
        return false;
    }

    function eventEmit() {
        // 新增 - 弹窗打开
        $('.btn-add').click(function () {
            //获取角色列表
            App.ajax({
                type: "POST",
                url: context + "/role/listRoleSelect",
                success: function (obj) {
                    var code = obj.code;
                    if (code == 0) {
                        var data = obj.data;
                        var html = [];
                        for (var i = 0; i < data.length; i++) {
                            var item = data[i];
                            html.push('<label style="margin-right:10px;"> <input class="input" type="checkbox" name="roleIds" value="' + item.roleId + '"> ' + item.roleName + ' </label>');
                        }
                        $('.roleIds').initTable(html,6);
                    }
                }
            })
            popup.open('.popup-add')
        })

        // 批量启用禁用用户
        $('.btn-batch-able, .btn-batch-disable').click(function () {
            var status = 0;
            var optName = "批量启用";
            if($(this).hasClass('btn-batch-disable')){
                status = 1;
                optName = "批量禁用";
            }

            let idArr = [];
            var hasSuperAdminUser = false;
            $('tbody [type="checkbox"]').each(function (index, element) {
                if (element.checked == true) {
                    var superAdminUser = $(this).parents('tr,.tr').data('superAdminUser');
                    var id = $(this).parents('tr,.tr').data('id');
                    console.log("superAdminUser:"+superAdminUser);
                    if(superAdminUser == 0){
                        //是超级管理员不能操作
                        hasSuperAdminUser = true;
                        return;
                    } else {
                        idArr.push(id);
                    }
                }
            })
            if(hasSuperAdminUser){
                popup.tipsTop('选择的用户中包含超级管理员，请确认', 'warning');
                return;
            }
            var ids = idArr.join(',');
            if(isBlank(ids)){
                popup.tipsTop('请选择需要'+optName+'的用户', 'warning');
                return;
            }
            //获取角色列表
            App.ajax({
                type: "POST",
                url: context + "/user/batchAbleDisable",
                data: {
                    ids: ids,
                    status: status
                },
                success: function (obj) {
                    var code = obj.code;
                    if (code == 0) {
                        popup.tipsTop((optName + '成功'), 'success');
                        setTimeout(function () {
                            //跳转到用户列表
                            window.location.href = context + "/user/list";
                        }, 1000);
                    } else {
                        popup.tipsTop(obj.msg, 'warning');
                    }
                }
            })
        })


        // 修改 - 弹窗打开
        $('.btn-detail').click(function () {
            var data = $(this).parents('tr')[0].dataset;
            //取值
            var userid = data["id"];
            var departmentid = data["departmentid"];
            var departmentname = (data["departmentname"] == undefined || null) ? "" : data["departmentname"];
            var username = data["username"];
            var realname = data["realname"];
            var mobilephone = data["mobilephone"];
            var email = data["email"];
            var belongroleids = data["belongroleids"];
            var status = data["status"];
            var userType=data["usertype"];
            console.log(userType);

            //获取角色列表
            App.ajax({
                type: "POST",
                url: context + "/role/listRoleSelect",
                success: function (obj) {
                    var code = obj.code;
                    if (code == 0) {
                        var data = obj.data;
                        var html = [];
                        for (var i = 0; i < data.length; i++) {
                            var item = data[i];
                            html.push('<label style="margin-right:10px;"> <input class="input" type="checkbox" name="roleIds" value="' + item.roleId + '"> ' + item.roleName + ' </label>');
                        }
                        $('.roleIds').initTable(html,4);


                        if (belongroleids != '') {
                            var data = belongroleids.split(',');
                            for (var i = 0; i < data.length; i++) {
                                var value = data[i];
                                var roleItem = $(".popup-detail input[name='roleIds'][value='" + value + "']")[0];
                                if(roleItem != null && roleItem != undefined){
                                    roleItem.checked = true;
                                }
                            }
                        }
                    }
                }
            })

            $('.popup-detail').html($('.popup-add').html()).find('.title').text('修改');
            $('.popup-detail').formLoad({
                // name: '测试',
                userId: userid,
                departmentId: departmentid,
                departmentName: departmentname,
                userName: username,
                realname: realname,
                mobilePhone: mobilephone,
                email: email,
                status: status,
                userType:userType
            })
            popup.open('.popup-detail');
            $('.pwd-item').html('<input type="password" value="" placeholder="请输入登陆密码" class="password" name="password" data-name="登录密码">');
            $('.pwd').hide();
        })

        // 选择部门
        var url = "/department/goDepartmentPickerPage"
        if (context) {
            url = context + url;
        }
        $(document).on('click', '.select-department', function () {
            layer.open({
                type: 2 //此处以iframe举例
                , title: '选择部门'
                , area: ['900px', '500px']
                , maxmin: true
                , content: url
                , btn: ['确定', '取消'] //只是为了演示
                , btnAlign: 'c'
                , yes: function (index, layero) {
                    // 获取layer中的数据
                    var iframeWin = window[layero.find('iframe')[0]['name']] //得到iframe页的窗口对象，执行iframe页的方法
                    // 用iframeWin.functionname() 调用窗口中的方法
                    // var data = iframeWin.getData()
                    var data = iframeWin.getTreeData();

                    $('input[name=departmentName]').val(data.namedata);
                    $('input[name=departmentId]').val(data.idsdata);

                    layer.close(index) //如果有数据，需进行手工关闭
                }
                , btn2: function (index, layero) {
                    layer.closeAll()
                }

                , zIndex: layer.zIndex //重点1
                , success: function (layero) {
                    layer.setTop(layero) //重点2
                }
            })

        })

    }


    // 新增 - 弹窗保存
    var form = $(".popup-add form").form({
        submitSelector: ".popup-add .btn-submit",
        msg: function (msg) {
            popup.tipsTop(msg, 'warning');
        },
        submit: function () {
            var data = {};
            $.each($(".popup-add form").serializeArray(), function (index, field) {
                if (data[field.name]) {
                    data[field.name] += "," + field.value;
                } else {
                    data[field.name] = field.value;
                }
            })
            App.ajax({
                type: "POST",
                url: context + "/user/save",
                data: data,
                success: function (obj) {
                    var code = obj.code;
                    if (code == 0) {
                        popup.tipsTop('创建用户成功', 'success');
                        setTimeout(function (args) {
                            //跳转到用户列表
                            window.location.href = context + "/user/list";
                        }, 500);
                    } else {
                        popup.tipsTop(obj.msg, 'warning');
                    }
                }
            })
        }
    })

    // 修改 - 弹窗确定
    var form = $(".popup-detail form").form({
        submitSelector: ".popup-detail .btn-submit",
        msg: function (msg) {
            popup.tipsTop(msg, 'warning');
        },
        submit: function () {
            var data = {};
            $.each($(".popup-detail form").serializeArray(), function (index, field) {
                if (data[field.name]) {
                    data[field.name] += "," + field.value;
                } else {
                    data[field.name] = field.value;
                }
            })
            //修改
            App.ajax({
                type: "POST",
                url: context + "/user/update",
                data: data,
                success: function (obj) {
                    var code = obj.code;
                    if (code == 0) {
                        popup.tipsTop('修改用户成功', 'success');
                        setTimeout(function (args) {
                            //跳转到用户列表
                            window.location.href = context + "/user/list";
                        }, 500);
                        $('.pwd').show();
                        $('.pwd-item').html('<input type="password" value="" placeholder="请输入登陆密码" class="password" name="password" data-name="登录密码" data-rule="required,password">');
                    } else {
                        popup.tipsTop(obj.msg, 'warning');
                    }
                }
            })
        }
    })


    // 重置密码 - 弹窗打开
    $('.btn-reset').click(function () {
        var data = $(this).parents('tr')[0].dataset;

        $(".popup-reset form").formLoad({
            userId:data.id,
        })
        popup.open('.popup-reset')
    })

    // 重置密码 - 弹窗确定
    var form = $(".popup-reset form").form({

        submitSelector: ".popup-reset .btn-submit",
        msg: function (msg) {
            popup.tipsTop(msg, 'warning');
        },
        submit: function () {
            var data = {};
            $.each($(".popup-reset form").serializeArray(), function (index, field) {
                if (data[field.name]) {
                    data[field.name] += "," + field.value;
                } else {
                    data[field.name] = field.value;
                }
            })
            App.ajax({
                type: "POST",
                url: context + "/user/resetPassword",
                data: {
                    userId:data.userId,
                    password:data.password
                },
                success: function (obj) {
                    var code = obj.code;
                    if (code == 0) {
                        popup.tipsTop('重置密码成功', 'success');
                        //关闭重置密码弹窗
                        popup.close('.popup-reset')
                    } else {
                        popup.tipsTop(obj.msg, 'warning');
                    }
                }
            })
        }
    })

    // 启用/禁用
    $('.btn-disable,.btn-enable').click(function () {
        var data = $(this).parents('tr')[0].dataset;
        var id = data["id"];
        //默认（0：启用）
        var status = 0;
        if ($(this).hasClass('btn-enable')) {
            App.ajax({
                type: "POST",
                url: context + "/user/enableDisableUser",
                data: {
                    userId: id,
                    status: status
                },
                success: function (obj) {
                    var code = obj.code;
                    if (code == 0) {
                        popup.tipsTop('enable', '启用用户成功');
                        //跳转到用户列表
                        window.location.href = context + "/user/list";
                    } else {
                        popup.tipsTop(obj.msg, 'warning');
                    }
                }
            })
        } else {
            //禁用
            status = 1;
            App.ajax({
                type: "POST",
                url: context + "/user/enableDisableUser",
                data: {
                    userId: id,
                    status: status
                },
                success: function (obj) {
                    var code = obj.code;
                    if (code == 0) {
                        popup.tipsTop('disable', '禁用用户成功');
                        //跳转到用户列表
                        window.location.href = context + "/user/list";
                    } else {
                        popup.tipsTop(obj.msg, 'warning');
                    }
                }
            })
        }
    })
</script>
</body>

</html>